package com.kotlin.hxh.base

import android.app.Activity
import android.content.Context
import androidx.fragment.app.Fragment
import com.kotlin.hxh.ui.fragment.first.ZhihuFirstFragment

/**
 * @author huxh
 * @date 2018/12/17.
 */
abstract class BaseMainFragment : Fragment() {

    var _mBackToFirstListener: OnBackToFirstListener? = null
    var _mActivity: Activity? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        _mActivity = activity
        if (context is OnBackToFirstListener) {
            _mBackToFirstListener = context
        } else {
            throw RuntimeException(context.toString() + " must implement OnBackToFirstListener")
        }
    }

    fun onBackPressedSupport(): Boolean {
        if (childFragmentManager.backStackEntryCount > 1) {
            childFragmentManager.popBackStack()
        } else {
            if (this is ZhihuFirstFragment) {
                _mActivity?.finish()
            } else {
                _mBackToFirstListener?.onBackToFirstFragment()
            }
        }
        return true
    }

    override fun onDetach() {
        super.onDetach()
        _mBackToFirstListener = null
    }

    fun popToChild(java: Class<Fragment>, b: Boolean) {
        childFragmentManager.popBackStack()
    }

    public interface OnBackToFirstListener {
        fun onBackToFirstFragment()
    }
}